import { useUserStore } from '@/store'
import Request, { type HttpMethod, type HttpRequestConfig } from 'luch-request'

export const baseURL = 'https://consult-api.itheima.net'

const service = new Request({
  baseURL: baseURL,
  timeout: 20 * 1000,
  custom: {
    loading: true,
  },
})

// 接口白名单
const whiteList = ['/code', '/login', '/login/password']

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (config.custom?.loading) {
      uni.showLoading({
        title: '加载中...',
        mask: true,
      })
    }

    // 添加token
    const store = useUserStore()
    if (store.token && !whiteList.includes(config.url as string)) {
      config.header = {
        ...config.header,
        Authorization: `Bearer ${store.token}`,
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    uni.hideLoading()
    // 统一错误处理，后端约定，code === 10000 为成功
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none',
      })
      return Promise.reject(res.data.message)
    }
    // 简化数据返回
    return res.data
  },
  (error) => {
    uni.hideLoading()
    if (error.data.code === 401) {
      uni.showToast({
        title: error.data.message,
        icon: 'none',
      })
      // 清楚token
      const store = useUserStore()
      store.clearToken()
      // 跳转到登录页
      uni.navigateTo({
        url: '/pages/login/login',
      })
    }
    return Promise.reject(error)
  }
)

export interface ServiceResponse<T> {
  code: number
  message: string
  data: T
}

const request = <T>(
  url: string,
  method: HttpMethod = 'GET',
  submitData?: object,
  config?: HttpRequestConfig
) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    ...config,
  })
}

export { service, request }
